#!/usr/bin/python2.6
"""Generates an hmac signature for a dumpcatcher add crash post."""

import copy
import hashlib
import hmac
import sys
import urlparse
import urllib
import urllib2


def send_crash(product_key, secret, url, *parameters):
  """Params should be a list of two-element tuples (k,v)."""
  # Add product_key to parameters.
  all_parameters = list(parameters) + [('product_key', product_key)]

  # Build hmac
  all_parameters.sort(key=lambda k: k[0])
  message = '&'.join(['%s=%s' % pair for pair in all_parameters])
  hmac_ = hmac.HMAC(secret, message, digestmod=hashlib.sha1)
  digest = hmac_.hexdigest()

  # Attach hmac to parameters.
  all_parameters += [('hmac', digest)]

  # Encode parameters
  request_data = urllib.urlencode(all_parameters)

  # Send request.
  request = urllib2.Request(url, data=request_data)
  return urllib2.urlopen(request)


def main():
  product_key = sys.argv[1]
  secret = sys.argv[2]
  url = sys.argv[3]

  parsed_url = urlparse.urlparse(url)
  parameters = urlparse.parse_qsl(parsed_url.query)
  return send_crash(product_key, secret, url.split('?')[0], *parameters)


def main2():
  secret = sys.argv[1]


if __name__ == '__main__':
  main()
